import paddle
from paddle.optimizer import Adam
from paddle import nn
from model import create_model
from dataset import load_data


# def test_model(model, criterion, val_loader, device, val_data):
#     with paddle.no_grad():
#         epoch_test_accuracy = 0
#         epoch_test_loss = 0
#
#         for data, label in val_loader:
#             data = paddle.to_tensor(data, place=device)
#             label = paddle.to_tensor(label, place=device)
#
#             test_output = model(data.astype("float32"))
#
#             test_loss = criterion(test_output, label.astype("float32"))
#
#             test_output = paddle.nn.functional.sigmoid(test_output)
#             acc = 0
#             for i in range(len(test_output)):
#                 if (
#                     paddle.round(test_output[i])
#                     == paddle.round(label[i].astype("float32"))
#                 ).all():
#                     acc += 1
#                 else:
#                     acc += 0
#
#             # print(acc)
#             # print(len(val_data))
#             epoch_test_accuracy += acc / len(val_data)
#             epoch_test_loss += test_loss.item()
#
#     # accmax.append(epoch_test_accuracy)
#     # accmax.sort(reverse=True)
#
#     # print(
#     #     f"[{epoch + 1}:{epochs}]|test_loss:{epoch_test_loss:.4f}|test_acc:{epoch_test_accuracy:.4f}"
#     # )
#     return epoch_test_accuracy


def test_model(model, criterion, val_loader, device):
    with paddle.no_grad():
        epoch_test_accuracy = 0
        epoch_test_loss = 0
        test_output = []
        for data, label in val_loader:
            data = paddle.to_tensor(data, place=device)
            label = paddle.to_tensor(label, place=device)

            test_output = model(data.astype("float32"))

            test_loss = criterion(test_output, label.astype("float32"))

            test_output = paddle.nn.functional.sigmoid(test_output)

            # 将 test_output 中的所有值四舍五入
            test_output = paddle.round(test_output)

            acc = 0
            for i in range(195):
                if paddle.round(test_output[0, i]) == paddle.round(
                    label[0, i].astype("float32")
                ):
                    acc += 1
                else:
                    acc += 0

            # print(acc)
            # print(len(val_data))
            epoch_test_accuracy += acc / 195
            epoch_test_loss += test_loss.item()

    return epoch_test_accuracy, test_output
